<template>
  <div class="container">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <el-breadcrumb separator="">
        <el-breadcrumb-item
          ><div class="div1">基本配置</div></el-breadcrumb-item
        >
        <el-breadcrumb-item
          ><div class="div2">店铺管理</div></el-breadcrumb-item
        >
      </el-breadcrumb>
    </div>
    <!-- 面包屑导航 teamManage -->
    <!-- 添加团队 -->
    <div class="content">
      <h2>店铺管理</h2>
      <h3>数据筛选</h3>
      <div>
        <el-form :inline="true" id="search" size="small">
          <el-form-item label="店铺名称">
            <el-input
              v-model="search.name"
              clearable
              placeholder="请输入店铺名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="店铺编码">
            <el-input
              v-model="search.code"
              clearable
              placeholder="请输入店铺编码"
            ></el-input>
          </el-form-item>
          <el-form-item label="所属平台">
            <el-select
              v-model="search.platformId"
              placeholder="请选择平台"
              clearable
            >
              <el-option
                v-for="item in platformList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="search.status"
              placeholder="请选择状态"
              clearable
            >
              <el-option
                v-for="item in dictionaries.enable_status"
                :key="item.dictId"
                :label="item.dictName"
                :value="item.dictId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="类目">
            <el-cascader
                :options="categoryList"
                v-model="search.classId"
                @change="onChangeCategory"
                filterable
                clearable
            ></el-cascader>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="fetchData('search')"
              >查询</el-button
            >
            <el-button
              type="primary"
              plain
              @click="fetchData('reset')"
              >重置</el-button
            ></el-form-item
          >
        </el-form>
      </div>
    </div>
    <div class="content">
      <h3 class="data-list-title">
        数据列表
        <el-button
            v-if="parArray.indexOf('addStore') != -1"
            size="small"
            type="primary"
            @click="showDialog('新增', 'add')"
        >新增</el-button
        >
      </h3>

      <!-- <div>{{ parArray.indexOf("authorityAdd") == 1 }}{{ parArray }}</div> -->
      <lb-table
        :column="column"
        :data="shopList"
        pagination
        :total="page.totalNum"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[5, 10, 20, 30, 50]"
        :current-page.sync="page.currentPage"
        :page-size="page.pageSize"
        @size-change="handleSizeChange"
        @p-current-change="handleCurrentChange"
      >
      </lb-table>
    </div>
    <!-- 管理客户等级 -->

    <!-- ============================= el-dialog ============================= -->
    <el-dialog
      :title="dialog.title"
      :visible.sync="dialog.visible"
      width="30%"
      :append-to-body="true"
      :before-close="handleClose"
      class="shop-dialog"
    >
      <div class="dialog-content">
        <div>
          <el-form :model="form" :rules="rules" ref="form" label-width="100px">
            <el-form-item label="店铺名称" prop="name">
              <el-input v-model="form.name" size="mini" maxlength="20" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="店铺编码" prop="code">
              <el-input v-model="form.code" size="mini" maxlength="6" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="所属平台" prop="platformId">
              <el-select
                v-model="form.platformId"
                placeholder="请选择所属平台"
                size="mini"
                clearable
              >
                <el-option
                  v-for="item in platformList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="所属分类" prop="classId">
              <el-cascader
                :options="categoryList"
                v-model="form.classId"
                @change="onChangeClassId"
                placeholder="请选择所属分类"
                size="mini"
                filterable
                clearable
              ></el-cascader>
            </el-form-item>
            <el-form-item label="序号" prop="sort">
              <el-input v-model.number="form.sort" size="mini"></el-input>
            </el-form-item>
            <el-form-item
              label="状态"
              prop="status"
              v-if="dialog.type === 'add'"
            >
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="item in dictionaries.enable_status"
                  :key="item.dictId"
                  :value="item.dictId"
                  :label="item.dictName"
                  :name="item.dictId"
                ></el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="dialogConfirm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- ============================= el-dialog end ============================= -->
  </div>
</template>

<script>
import { checkCode, checkSort } from '@/utils/rules.js';
import LbTable from '../../../components/lb-table/lb-table'
export default {
  name: 'role',
  components: { LbTable },
  data () {
    return {
      search: {
        code: '', // 店铺编码
        platformId: '', // 所属平台（数据来自接口《平台管理-平台列表查询接口》）
        status: '', // 状态（字典分组：enable_status）
        classId: '', // 类目（来源【类目管理】）
        name: '', // 名称
      },
      shopList: [], // 店铺列表
      platformList: [], // 平台列表
      categoryList: [], // 目类列表
      column: [
        { label: '所属平台', prop: 'platformName' },
        { label: '店铺编码', prop: 'code' },
        { label: '店铺名称', prop: 'name' },
        { label: '序号', prop: 'sort' },
        { label: '类目', prop: 'className' },
        {
          label: '状态',
          render: (h, scope) => {
            return (
              <div>
                <el-link size="mini" type={scope.row.status === 1 ? 'success' : 'danger'}>{scope.row.statusLabel}</el-link>
              </div>
            )
          }
        },
        { label: '最后更新时间', prop: 'updatedTime' },
        {
          label: '操作',
          render: (h, scope) => {
            return (
              <div>
                <el-link size="mini" type="primary" onClick={() => { this.showDialog('编辑', 'edit', scope.row, scope.$index) }}>编辑</el-link>
                <el-link size="mini" type="danger" onClick={() => { this.onDelete(scope.row, scope.$index) }}>删除</el-link>
                <el-link size="mini" type="primary" onClick={() => { this.changeStatus(scope.row, scope.$index) }} >{scope.row.status === 1 ? "禁用" : "启用"}</el-link>
              </div>
            )
          }
        }],
      page: { pageNo: 1, pageSize: 10, totalNum: 0, currentPage: 1 },
      dialog: { visible: false, title: "编辑", type: '' },
      form: {
        name: '', // 店铺名称 string
        code: '', // 店铺编码 string
        platformId: '', // 所属平台（数据来自接口《平台管理-平台列表查询接口》） int
        classId: '', // 所属分类 int
        sort: '', // 序号 int
        status: '' // 状态（字典分组：enable_status） int
      },
      rules: {
        name: [
          { required: true, message: '请输入平台名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入平台编码', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' },
          { validator: checkCode, message: '只能输入数字或英文字母',trigger: 'blur' },
          { validator: checkCode, message: '只能输入数字或英文字母',trigger: 'change' }
        ],
        platformId: [{ required: true, message: '请选择所属平台', trigger: 'change' }],
        classId: [{ required: true, message: '请选择所属分类', trigger: 'change' }],
        sort: [{ validator: checkSort, trigger: 'blur' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }],
      },
      dictionaries: { // 字典数据
        enable_status: [] // 状态
      },
      parArray: [] // 按钮权限
    };
  },
  created () {
    this.fetchData()
    this.getPlatformList() // 获取平台列表
    this.getCategoryList() // 获取目类列表
    this.getButtonTreeDto() // 获取权限设定
    // 获取字典值
    for (let type in this.dictionaries) { this.getDictionaries(type) }
  },
  /*
  watch: {
    permissionFilterText (val) {
      this.$refs.tree.filter(val);
    }
  },
  */
  methods: {
    fetchData (type) {
      if (type == 'reset') {
        this.search = {
          code: '', // 店铺编码
          platformId: '', // 所属平台（数据来自接口《平台管理-平台列表查询接口》）
          status: '', // 状态（字典分组：enable_status）
          classId: '', // 类目（来源【类目管理】）
          name: '', // 名称
        }
        this.page.pageNo = 1
        this.page.pageSize = 10
        this.page.currentPage = 1
      }
      let params = {
        pageNo: this.page.pageNo,
        pageSize: this.page.pageSize
      }
      if (type == 'search') {
        this.page.currentPage = 1
        this.page.pageNo = 1
        params.pageNo = 1
        const search = this.search
        params = Object.assign(params, search);
        // 去除字符串 前后 空格
        for (let item in params) { if(typeof params[item] === "string"){ params[item] = params[item].trim() } }
      }
      this.$api.shopList(params).then((res) => {
        if (res.code === 0) {
          this.shopList = res.data.list
          this.page.totalNum = res.data.totalNum
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    handleCurrentChange (currentChange) {
      this.page.pageNo = currentChange
      this.fetchData()
    },
    handleSizeChange (sizeChange) {
      this.page.pageSize = sizeChange
      this.fetchData()
    },
    // 获取平台列表
    getPlatformList () {
      const params = {}
      this.$api.platformDataList(params).then((res) => {
        this.platformList = res.data
      }).catch((err) => {
        console.log(err)
      })
    },
    // 获取类目列表
    getCategoryList () {
      const params = {}
      this.$api.categoryList(params).then((res) => {
        /*
        res.data.list.forEach((e) => { // 一级
          e.label = e.categoryName
          e.value = e.id
          if(e.children && e.children.length > 0){
            e.children.forEach((ee) => {  // 二级
              ee.label = ee.categoryName
              ee.value = ee.id
                ee.children.forEach((eee) => {  // 三级
                  eee.label = eee.categoryName
                  eee.value = eee.id
                })
            })
          }
        })
        */
        this.categoryList = res.data.list
      }).catch((err) => {
        console.log(err)
      })
    },
    getButtonTreeDto () {
      // 获取权限设定
      this.limits = JSON.parse(sessionStorage.getItem('limit'))
      const params = this.limits.buttonTreeDto.filter(
        (item) => item.menuCode === 'shopCode'
      )
      params[0].buttonList.forEach((item) => {
        this.parArray.push(item.code)
      })
      console.log(this.parArray)
    },
    // 获取字典数据
    getDictionaries (type) {
      if (type && this.dictionaries[type].length > 0) { return }
      const params = { groupId: type }
      this.$api.dictionaries(params).then((res) => {
        this.dictionaries[type] = res.data
      }).catch((err) => {
        console.log(err)
      })
    },
    // 显示  dialog
    showDialog (title, type, row) {
      // console.log(title, type, row)
      this.dialog.type = type
      this.currentRow = row
      if (type == 'edit') {
        if (this.parArray.indexOf("editStore") == -1) { return this.$message({ type: 'warning', message: '没有权限请联系管理员!' }); }
        this.dialog.visible = true;
        this.dialog.title = '编辑'
        this.form = row
        this.onChangeEditClassId(row.classId)
      }
      if (type == 'add') {
        if (this.parArray.indexOf("addStore") == -1) { return this.$message({ type: 'warning', message: '没有权限请联系管理员!' }); }
        this.dialog.visible = true;
        this.dialog.title = '新增'
        this.form = {
          name: '', // 店铺名称 string
          code: '', // 店铺编码 string
          platformId: '', // 所属平台（数据来自接口《平台管理-平台列表查询接口》） int
          classId: [], // 所属分类 int
          sort: '', // 序号 int
          status: this.dictionaries.enable_status[0].dictName // 状态（字典分组：enable_status） int
        }
      }
      this.$refs["form"].resetFields();
    },
    // 修改 回显 classId
    onChangeEditClassId (classId) {
      console.time("回显 classId", classId)
      const categoryList = this.categoryList
      if (categoryList.length < 0) { console.log("categoryList没到位！", categoryList) }
      let arr = []
      categoryList.forEach((firstItem, firstIndex) => {
        if (firstItem.id === classId) {
          arr.push(firstItem.id)
          return
        }
        if (firstItem.children) {
          firstItem.children.forEach((secondItem, secondIndex) => {
            if (secondItem.id === classId) {
              arr.push(firstItem.id)
              arr.push(secondItem.id)
              return
            }
            if (secondItem.children) {
              secondItem.children.forEach((thirdItem, thirdIndex) => {
                if (thirdItem.id === classId) {
                  arr.push(firstItem.id)
                  arr.push(secondItem.id)
                  arr.push(thirdItem.id)
                  return
                }
              }) // third end
            }
          }) // second end
        }
      }) // first end
      this.form.classId = arr
      console.timeEnd("回显 classId")
    },
    // 修改 classId
    onChangeClassId (e) {
      console.log(e)
    },
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => { });
    },
    // 确认后判断各类操作
    dialogConfirm () {
      const type = this.dialog.type
      switch (type) {
        case 'add':
          this.submitForm('form', "add")
          break;
        case 'edit':
          this.submitForm('form',"edit")
          break;
        default:
          console.log(type)
      }
    },
    // 表单验证
    submitForm (formName,type) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // console.log(this.addPermissionForm.name)
          if(type === "edit"){return this.editShop()}
          this.addShop()
          // console.log('submit!', valid, this.addPermissionForm.name);
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 添加店铺
    addShop () {
      const params = this.form
      params.status = this.dictionaries.enable_status.find((e) => e.dictName === params.status || e.dictName == params.status).dictId
      // const params = { name: permissionForm.name, dataPermission: permissionForm.dataPermission, salesAuthorityId: permissionForm.salesAuthorityId }
      params.classId = this.form.classId[this.form.classId.length - 1]
      this.$api.shopAdd(params).then((res) => {
        if(res.code === 0){
          this.form = {
            name: '', // 店铺名称 string
            code: '', // 店铺编码 string
            platformId: '', // 所属平台（数据来自接口《平台管理-平台列表查询接口》） int
            classId: '', // 所属分类 int
            sort: '', // 序号 int
            status: '' // 状态（字典分组：enable_status） int
          }
          this.dialog.visible = false;
          this.fetchData()
          this.$message({ type: 'success', message: '操作成功!' });
        }


      }).catch((err) => {
        this.form.status = this.dictionaries.enable_status.find((e) => e.dictId == params.status || e.dictName == params.status).dictName
        console.log(err)
      })
    },
    // 编辑
    editShop () {
      const params = this.form
      // if (typeof params.status !== Number) { params.status = this.dictionaries.enable_status.find((e) => e.dictName === params.status).dictId }
      // console.log(params)
      // const params = { name: permissionForm.name, dataPermission: permissionForm.dataPermission, salesAuthorityId: permissionForm.salesAuthorityId }
      params.classId = this.form.classId[this.form.classId.length - 1]
      this.$api.shopUpdate(params).then((res) => {
        if(res.code === 0){
          this.dialog.visible = false;
          this.fetchData()
          this.$message({ type: 'success', message: '编辑成功!' });
        }
      }).catch((err) => {
        this.fetchData()
        console.log(err)
      })
    },
    // 删除
    onDelete (item, index) {

      if (this.parArray.indexOf("deleteStore") == -1) { return this.$message({ type: 'warning', message: '没有权限请联系管理员!' }); }
      this.$confirm('此操作将删除选中的权限组, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = { id: item.id }
        this.$api.shopDelete(data).then((res) => {
          this.fetchData()
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch((err) => {
          console.log(err)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 修改状态
    changeStatus (item, index) {
      const data = { id: item.id }
      // 禁用
      if (item.status === 1) {
        if (this.parArray.indexOf("storeDisabled") == -1) { return this.$message({ type: 'warning', message: '没有权限请联系管理员!' }); }

        this.$api.shopDisable(data).then((res) => {
          this.fetchData()
          this.$message({
            message: `已禁用【${item.name}】!`
          });
        }).catch((err) => {
          console.log(err)
        })
      }

      // 启用
      if (item.status === 2) {
        if (this.parArray.indexOf("openStore") == -1) { return this.$message({ type: 'warning', message: '没有权限请联系管理员!' }); }

        this.$api.shopEnable(data).then((res) => {
          this.fetchData()
          this.$message({
            type: 'success',
            message: `启用【${item.name}】成功!`
          });
        }).catch((err) => {
          console.log(err)
        })
      }
    },
    // 搜索 选择 类目
    onChangeCategory (val) {
      this.search.classId = val[val.length -1]
      console.log(val, this.search.classId)
    },
  }
}
</script>

<style scoped lang="scss">
.div1 {
  margin-left: -16px;
  background: url(../../../assets/breadcrumb2.png);
  width: 120px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  color: #2d7edf;
}
.div2 {
  margin-left: -16px;
  background: url(../../../assets/breadcrumb1.png);
  width: 120px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  color: #fff;
}
.div3 {
  margin-left: -8px;
  background: url(../../../assets/breadcrumb3.png);
  width: 120px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  color: #2d7edf;
}
//
//#search{
//  display: flex;
//  .el-form-item{
//    flex: 1;
//    .el-form-item__content{
//      width: 80%;
//    }
//  }
//}

.content {
  .el-button {
    margin-bottom: 10px;
  }
  .el-badge {
    margin-left: 10px;
  }
}
.roleList {
  border: 1px solid #f0f3fd;
  border-radius: 5px;
  .title {
    color: #333333;
    line-height: 40px;
    padding: 0 10px;
    background-color: #f0f3fd;
    .el-badge {
      margin-top: 10px;
      margin-left: 10px;
    }
  }
  .list {
    padding: 20px;
    .el-tag {
      border: 0;
      margin-right: 10px;
      margin-bottom: 10px;
    }
  }
}
.dialog-content {
  // min-height: 210px;
  .el-tree {
    max-height: 300px;
    overflow: auto;
  }
  .el-radio {
    // display: block;
    // margin: 8px 0;
  }
}
</style>
<style lang="scss">
.content {
  .el-link {
    margin: 0 5px;
  }
  h4 {
    padding-top: 10px;
    border-top: 1px solid #bbbbbb;
  }
}
</style>
